//
//  PhotoController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 16/4/20.
//  Copyright © 2016年 sgone. All rights reserved.
//

#import "PhotoController.h"
#import "HPReleaseCommentScrollView.h"
#import "ShareComposePhotos.h"
#import "UIImage+Addition.h"
//#import "JKImagePickerController.h"
#import "JKImagePicker2Controller.h"
#import "IQKeyboardManager.h"
#import "ACTextView.h"
#import "UIScrollView+UITouch.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "FDAlertView.h"
#import "MBProgressHUD.h"

#import "UIImageView+AFNetworking.h"
#import "QiniuSDK.h"



#define QINIUNAMEURL @"http://fruitsimage.qiniudn.com/"

@interface PhotoController () <UIImagePickerControllerDelegate,JKImagePickerControllerDelegate,UITextViewDelegate,UIScrollViewDelegate,UIActionSheetDelegate,addImageClickDelegate,UINavigationControllerDelegate> {
    
    NSMutableArray *imageNameArray;
    IQKeyboardManager *manager2;
}

@property (nonatomic, strong)UIButton *backButton;
@property (nonatomic, strong)UIButton *sendButton;

@property (nonatomic, strong) NSMutableArray *assetsArray;

/** 相册(存放拍照或者相册中选择图片) */
@property (nonatomic, strong) ShareComposePhotos *photosView;

@property (nonatomic, strong) HPReleaseCommentScrollView *scrollView;

////上传七牛服务器
@property (nonatomic, strong) QNUploadManager *uploader;
//获得七牛的token的数据
@property(nonatomic,strong) NSString *QNtoken;
//上传到七牛服务器所进行的拼接字符串
@property (nonatomic, strong) NSMutableArray *nameKey;
//上传到七牛形成的网络路径
@property (strong, nonatomic)NSMutableArray *filePath;

@property (nonatomic, strong)UIImagePickerController *imageControl;
@property (nonatomic, strong)AFHTTPSessionManager *manager;



@end

@implementation PhotoController



- (AFHTTPSessionManager *)manager {
    
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}




- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}


- (NSMutableArray *)filePath {
    
    if (_filePath == nil) {
        
        _filePath = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _filePath;
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    

 
    [self setNavigationBarView];
    
    manager2.enable = NO;
    //    manager.shouldResignOnTouchOutside = YES;
    //    manager.shouldToolbarUsesTextFieldTintColor = YES;
    //    manager.enableAutoToolbar = NO;
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hideRightButton" object:nil userInfo:@{@"state":@"0"}];
}



- (void)setNavigationBarView {
    
    CGFloat width = 30 / FDLaOt;
    self.backButton = [[UIButton alloc] initWithFrame:CGRectMake(16, 20 + (44 - width) / 2, width, width)];
    [self.backBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self.backButton setTitle:@"取消" forState:UIControlStateNormal];
    self.backButton.titleLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
    [self.backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.backButton];

    
    self.sendButton = [[UIButton alloc] initWithFrame:CGRectMake( ViewWidth - 16 - width, 20 + (44 - width) / 2, width, width)];
    [self.sendButton setTitle:@"发送" forState:UIControlStateNormal];
    self.sendButton.titleLabel.font = [UIFont systemFontOfSize:14 / FDLaOt];
    [self.sendButton addTarget:self action:@selector(sendClick) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.sendButton];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.backButton removeFromSuperview];
    [self.sendButton removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hideRightButton" object:nil userInfo:@{@"state":@"1"}];
    manager2.enable = YES;
}





- (void)viewDidLoad {
    [super viewDidLoad];
    imageNameArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.nameKey = [[NSMutableArray alloc] initWithCapacity:0];


    
    [self creatUI];
    
    
}



-(void)creatUI
{
    self.titleLabel.text = @"水果圈";
//    self.backBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//    [self.backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
//    [self.backBtn setTitle:@"取消" forState:UIControlStateNormal];
//    [self.backBtn setFrame:CGRectMake(18, 20, 44, 44)];
//    [self.topView addSubview:self.backBtn];
//    self.backBtn.hidden = NO;
//    self.backBtn.titleLabel.font = [UIFont systemFontOfSize:16/FDLaOt];
//    
//    
//    
//    self.rightBut.hidden = NO;
//    [self.rightBut setFrame:CGRectMake(ViewWidth -60, 20, 44, 44)];
//    [self.rightBut setTitle:@"发送" forState:UIControlStateNormal];
//    self.rightBut.titleLabel.font = [UIFont systemFontOfSize:16/FDLaOt];
    
    
    
    //添加输入控件
    [self setupTextView];
    
    //添加相册
    [self setupPhotosView];

}

/**
 *  @author jing
 *
 *  @brief  添加输入控件
 */
- (void)setupTextView
{
    
    self.scrollView = [[HPReleaseCommentScrollView alloc] initWithFrame:CGRectMake(0, 64, ViewWidth, ViewHeight - 64)];
    self.scrollView.delegate = self;
    self.scrollView.addDelegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = NO;
    self.scrollView.contentSize = CGSizeMake(ViewWidth, ViewHeight);
    self.scrollView.userInteractionEnabled = YES;
    self.scrollView.maxLength = 700;
    [self.view addSubview:self.scrollView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoardTap)];
    tapGesture.numberOfTapsRequired = 1;
    tapGesture.numberOfTouchesRequired = 1;
    [self.scrollView addGestureRecognizer:tapGesture];
    
    [self.scrollView.contentTextView becomeFirstResponder];
}
/**
 *  @author jing
 *
 *  @brief  添加相册
 */
- (void)setupPhotosView
{
    ShareComposePhotos *photosView = [[ShareComposePhotos alloc] init];
    photosView.x = self.scrollView.addImageButton.width + self.scrollView.addImageButton.x;
    photosView.y = 130 / FDLaOt;
    photosView.width = ViewWidth - photosView.x;

    photosView.height = ViewHeight;

    
    [self.scrollView addSubview:photosView];
    self.photosView = photosView;
}


- (void)openCamera
{
    [self openImagePickerController:UIImagePickerControllerSourceTypeCamera];
}



- (void)openAlbum
{
    // 如果想自己写一个图片选择控制器，得利用AssetsLibrary.framework，利用这个框架可以获得手机上的所有相册图片
    // UIImagePickerControllerSourceTypePhotoLibrary > UIImagePickerControllerSourceTypeSavedPhotosAlbum
    
    //    [self openImagePickerController:UIImagePickerControllerSourceTypePhotoLibrary];
    [self composePicAdd];
}


- (void)openImagePickerController:(UIImagePickerControllerSourceType)type
{
    if (![UIImagePickerController isSourceTypeAvailable:type])
        
        return;
    
    _imageControl = [[UIImagePickerController alloc]init];
    _imageControl.sourceType = UIImagePickerControllerSourceTypeCamera;
    _imageControl.delegate = self;
    _imageControl.allowsEditing = YES;
    
    [self addChildViewController:_imageControl];
    [self.view addSubview:_imageControl.view];
    
    //    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    //    ipc.sourceType =type;
    //    ipc.delegate =self;
    //    [self presentViewController:ipc animated:YES completion:nil];
    //    [self.navigationController pushViewController:ipc animated:YES];
    //    [self addChildViewController:ipc];
    //    [self.view addSubview:ipc.view];
    
}




#pragma mark - UIImagePickerControllerDelegate
/**
 * 从UIImagePickerController选择完图片后就调用（拍照完毕或者选择相册图片完毕）
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //    [picker dismissViewControllerAnimated:YES completion:nil];
    //    [picker.navigationController popViewControllerAnimated:YES];
    [picker.view removeFromSuperview];
    
    //info中就包含了选择的图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    //添加图片到photoView中
    [self.photosView addPhoto:image];
    
    self.scrollView.addImageLable.hidden = YES;
    
    self.navigationController.navigationBar.hidden= YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
}

- (void)imagePickerController:(JKImagePicker2Controller *)imagePicker didSelectAssets:(NSArray *)assets isSource:(BOOL)source
{
    
    self.assetsArray = [NSMutableArray arrayWithArray:assets];
    
    if (self.assetsArray.count + self.photosView.photos.count > 0) {
        
        self.scrollView.addImageLable.hidden = YES;
    } else {
        
        self.scrollView.addImageLable.hidden = NO;
    }
    if (self.assetsArray.count + self.photosView.photos.count > 9) {
//        [MBProgressHUD showError:@"最多选取9张图片"];
        
        [self.view makeToast:@"最多选取9张图片"];
        
    } else {
        
        for (int i = 0; i < self.assetsArray.count; i++) {
            JKAssets *asset = self.assetsArray[i];
            
            ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
            [lib assetForURL:asset.assetPropertyURL resultBlock:^(ALAsset *asset) {
                if (asset) {
                    UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage]];
                    
                    [self.photosView addPhoto:image];
                    if (i == self.assetsArray.count-1) {
                        //                        [imagePicker dismissViewControllerAnimated:YES completion:nil];
                        [imagePicker.navigationController popViewControllerAnimated:YES];
                    }
                    
                }
            } failureBlock:^(NSError *error) {
                
            }];
        }
    }
}

- (void)composePicAdd
{
    JKImagePicker2Controller *imagePickerController = [[JKImagePicker2Controller alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.showsCancelButton = YES;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.minimumNumberOfSelection = 1;
    imagePickerController.maximumNumberOfSelection = 9;
    imagePickerController.selectedAssetArray = self.assetsArray;
    //    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    //    [self presentViewController:navigationController animated:YES completion:nil];
    [self.navigationController pushViewController:imagePickerController animated:YES];
}




- (void)imagePickerControllerDidCancel:(JKImagePicker2Controller *)imagePicker
{
    //    [imagePicker dismissViewControllerAnimated:YES completion:nil];
    //    [imagePicker.navigationController popViewControllerAnimated:YES];
    
    if (_imageControl) {
        
        [_imageControl.view removeFromSuperview];
        self.navigationController.navigationBar.hidden=YES;
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    }
    
    [imagePicker.view removeFromSuperview];
}


- (void)imagePickerControllerCancel:(JKImagePicker2Controller *)imagePicker {
    
    
    [imagePicker.navigationController popViewControllerAnimated:YES];
}

- (void)backClick {
    
    //    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sendClick {
    
    [self getQiniuToken];
}



#pragma  mark获取七牛的token
//通过七牛上传图片
- (void)getQiniuToken {
    
    NSString *str = [NSString stringWithFormat:@"http://app.sgone.cn/appapi_v4/wholesaler_common/get_private_storage_token"];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError || data == nil) {
            
            return ;
        }
        //解析服务器返回来的json数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        
        NSString *token = [[dict objectForKey:@"data"] objectForKey:@"upToken"];
        NSNumber *expire = [[dict objectForKey:@"data"] objectForKey:@"expire"];
        
        self.QNtoken = token;
        
        if (token != nil) {
            
            if (self.photosView.photos.count == 0 && self.scrollView.contentTextView.text.length == 0) {
                
//                [MBProgressHUD showError:@"请输入图片或文字"];
                [self.view makeToast:@"请输入图片或文字"];
                return;
            }
            
            self.sendButton.enabled = NO;
            if (self.photosView.photos.count > 0) {
                
                for (int i = 0; i < self.photosView.photos.count; i++) {
                    
                    [self.filePath addObject:[self dataFilePath:[NSString stringWithFormat:@"%@%d.jpg",[self getTimeString],i]]];
                    NSData *webData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((UIImage *)[self.photosView.photos[i] image], 0.5)];
                    [webData writeToFile:self.filePath[i] atomically:YES];
                }
                [self uploadImage];
            } else
                
                [self sendShareToService];
        }
    }];
}


//网络上传到七牛的操作步骤以及属性
#pragma mark - upload qiniu
- (void)uploadImage{
    
    //获得的商品图片，需要传递给服务器
    for (int i = 0; i < _filePath.count; i++) {
        
        [self.nameKey addObject:[NSString stringWithFormat:@"FD%@-%@-%d.jpg",[[NSUserDefaults standardUserDefaults] objectForKey:@"phone"], [self getTimeString],i]];
    }
    
    if (!self.uploader) {
        
        self.uploader = [[QNUploadManager alloc]init];
    }
    
//    [MBProgressHUD showSuccess:@"开始上传图片请等待"];
    [self.view makeToast:@"开始上传图片请等待"];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        for (int i = 0; i < _filePath.count; i++) {
            
//            NSLog(@"dashdsahd  %@",self.nameKey[i]);
            
            [self.uploader putFile:[_filePath objectAtIndex:i] key:self.nameKey[i] token:self.QNtoken complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [imageNameArray addObject:[NSString stringWithFormat:@"%@%@",QINIUNAMEURL,key]];
                    
                    if (imageNameArray.count == _filePath.count) {
                        
                        [MBProgressHUD hideAllHUDsForView:self.scrollView animated:YES];
                        [self sendShareToService];
                    }
                });
            } option:nil];
        }
    });
}


- (void)sendShareToService {
    
    if (self.scrollView.contentTextView.text.length == 0) {
        
        self.scrollView.contentTextView.text = @"";
    }
    
    NSString *imageListStr = nil;
    
    if (self.photosView.photos.count > 0) {
        
        if (self.photosView.photos.count > 1) {
            
            imageListStr = [imageNameArray componentsJoinedByString:@"|"];
        } else
            imageListStr = [imageNameArray lastObject];
    } else {
        
        imageListStr = [NSNull null];
    }
    
    __weak PhotoController *weakSelf = self;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        
        
        NSString *url = [NSString stringWithFormat:@"%@add_fruit_frend_list",SERVER_ADDRESS3];
        NSDictionary *pramas = @{@"tel" : self.dataHandler.phone ,@"uid" : [self.dataHandler.userDic objectForKey:@"wId"] , @"body" : self.scrollView.contentTextView.text , @"imglist" :imageListStr , @"lat" : @"" , @"lng" : @"", @"user_type" : @"3"};
        
        
        [self.manager POST:url parameters:pramas success:^(NSURLSessionDataTask *task, id responseObject) {
            
            if ([responseObject[@"error_flag"] intValue] == 0) {
                
                 [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
           
                UIAlertView *alter  = [[UIAlertView alloc]initWithTitle:@"提示" message:@"上传成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alter show];
                [self.navigationController popViewControllerAnimated:YES];
                
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshShareListMethod" object:nil];
                
            }
            else
            {
                
                
                 [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
                NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
                [self.view makeToast:str];
                
            
            
            
            }
            
            
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
            
             [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
            [self.view makeToast:@"请检查网络!"];
            

            
        }];

        
            
       
        
                
             
                
                
     
        
        
        
        /*
        [service setShareMessageByBody:self.scrollView.contentTextView.text imglist:imageListStr lat:@"" lng:@"" user_type:@"3" success:^(NSString *resultStr) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideAllHUDsForView:weakSelf.scrollView animated:YES];
                
                weakSelf.rightBut.enabled = YES;
                if ([resultStr isEqualToString:@"success"]) {
                    
                    [MBProgressHUD showSuccess:@"发送成功"];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshShareListMethod" object:nil];
                }
            });
        } error:^(NSString *errorInfo) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideAllHUDsForView:weakSelf.scrollView animated:YES];
                weakSelf.rightBut.enabled = YES;
                [OtherLogin otherUserLoginTheSameUsername:errorInfo navigationController:weakSelf.navigationController];
            });
        }];
        
      */
        
    });
         
         
    
    
}

//获得当前的时间
- (NSString *)getTimeString {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: @"yyMMddHHmmss"];
    return [formatter stringFromDate:[NSDate date]];
}



//进行数据持久化的保存，获得相应的目录路径
- (NSString *)dataFilePath:(NSString *)fileName {
    
    NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths1 objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:fileName];
}




- (void)addImageClick {
    
    [self.view endEditing:YES];
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选取", nil];
    [actionSheet showInView:self.scrollView];
}



- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (buttonIndex == 0) {
        
        [self openCamera];
    } else if (buttonIndex == 1) {
        
        if (self.photosView.photos.count == 9) {
//            [MBProgressHUD showError:@"最多添加9张图片"];
            [self.view makeToast:@"最多添加9张图片"];
        }else{
            [self openAlbum];
        }
    }
}



- (void)hideKeyBoardTap {
    
    [self.view endEditing:YES];
}




@end
